package org.client;

import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.common.dispatcher.ProtoDispatcher;
import org.common.netty.BaseNettyHandler;
import org.common.netty.Pack;
import org.common.netty.PackCodec;
import org.common.utils.SpringUtils;

@Slf4j
public class ClientNettyHandler extends BaseNettyHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, byte[] msg) throws Exception {
        Pack decode = PackCodec.decode(msg);
        log.info("receive client up msg. cmdId = {}", decode.getCmdId());
        byte[] data = decode.getData();
        ProtoDispatcher dispatcher = SpringUtils.getBean(ProtoDispatcher.class);
        Pack pack = dispatcher.dispatch(decode.getCmdId(), data, ctx.channel());
        if (pack != null) {
            ctx.channel().writeAndFlush(PackCodec.encode(pack));
        }
    }
}
